// package/pages/recharge/recharge.js
const utils = require('../../../utils/util.js');
let myRequest = require('../../../common/script/myRequest.js');
let api = require('../../../common/script/api.js');
let login = require('../../../common/script/login');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    objectArray: [],
    couponList: [],
    inpVal: '',
    money: '',
    id: '',
    totalamount: 0,
    orgcode: "",
    inputType: false,
    // isfoundingmember: false,
    discount: 0, //1：是创世卡，0不是创世卡
    discountdesc: '', //创世卡几折描述
    realmoney: '', //创世卡支付金额
    rulediscount: 1, //创世卡几折
    rechargeList: [],
    sale_money: ""
  },
  //获取是否创世会员价
  getRechargePay() {
    const that = this;
    let data = {
      ali_openid: '',
      ali_appid: '',
      in_money: that.data.money
    }
    myRequest.EasyHttp.post(api.reqUrls.getRechargePayMoneyAmount, data).then(res => {
      if (res.data.status == 1) {
        that.setData({
          discount: res.data.result.initmember.discount, //1：是创世卡，0不是创世卡
          discountdesc: res.data.result.initmember.discountdesc, //创世卡几折描述
          realmoney: res.data.result.initmember.realmoney, //创世卡支付金额
          rulediscount: res.data.result.initmember.rulediscount, //创世卡几折
          rechargeList: res.data.result.recharge_sale
        })
      }
    })
  },
  // 计数支付金额
  getBtnMoney() {
    const that = this;
    if (that.data.discount == 1) {
      let rechargeArr = that.data.rechargeList.filter(res => {
        return res.max_money >= that.data.money && res.min_money <= that.data.money
      })
      let yhMoney = parseFloat(that.data.money)
      let csMoney = parseFloat(that.data.money) * that.data.rulediscount
      if (rechargeArr.length > 0) {
        yhMoney = parseFloat(that.data.money) - rechargeArr[0].sale_money
        console.log(yhMoney, csMoney, 8888)
        // 如果创始会员金额小于优惠金额
        if (yhMoney >= csMoney) {
          console.log(1111)
          that.setData({
            btnMoney: csMoney.toFixed(2),
            sale_money: '',
          })
        } else {
          console.log(2222)
          that.setData({
            btnMoney: yhMoney.toFixed(2),
            sale_money: '优惠' + rechargeArr[0].sale_money + "元",
          })
        }
      } else {
        that.setData({
          btnMoney: csMoney.toFixed(2),
          sale_money: '',
        })
      }
    } else {
      let rechargeArr = that.data.rechargeList.filter(res => {
        return res.max_money >= that.data.money && res.min_money <= that.data.money
      })
      if (rechargeArr.length > 0) {
        rechargeArr.sort((a, b) => b.sale_money - a.sale_money);
        that.setData({
          btnMoney: (parseFloat(that.data.money) - rechargeArr[0].sale_money).toFixed(2),
          sale_money: '优惠' + rechargeArr[0].sale_money + "元"
        })
      } else {
        that.setData({
          btnMoney: parseFloat(that.data.money).toFixed(2),
          sale_money: ''
        })
      }
    }

  },

  bindFocusInput(e) {
    const that = this;
    let objectArray = that.data.objectArray
    objectArray.forEach(res => {
      res.checked = false
    })
    that.setData({
      inputType: true,
      // inpVal: '',
      // money: '',
      realmoney: '',
      objectArray: objectArray,
      id: '',
      couponList: [],
      // sale_money: '',
    })
  },
  bindKeyInput(e) {
    const that = this;
    let inpVal = e.detail.value ? parseInt(e.detail.value).toString() : ''
    that.setData({
      money: inpVal,
      inpVal,

    })
    that.getBtnMoney()
  },
  //获取余额
  getCardinfoData() {
    const that = this; 
    // const isfoundingmember = wx.getStorageSync('isfoundingmember');
    const totalamount = wx.getStorageSync('totalamount');
    that.setData({
      totalamount,
      // isfoundingmember
    })
  },
  //获取充值金额列表
  getProvince() {
    const that = this;
    let data = {
      orgcode: that.data.orgcode,
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getInMoneyType, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        var data = res.data.result.money_type;
        if (data) {
          var monerArr = [];
          for (var i = 0; i < data.length; i++) {
            data[i]['couponList'].forEach(prop => {
              prop.type = 1
            })
            data[i]['giftList'].forEach(prop => {
              prop.type = 2
            })
            var dec = {
              'id': data[i]['id'],
              'name': data[i]['money'],
              'des': data[i]['money'] + '元 ',
              'checked': false,
              couponList: [...data[i]['couponList'], ...data[i]['giftList']]
            }
            monerArr.push(dec)
          }
          that.setData({
            objectArray: monerArr,
          })
        }
      }
    })
  },
  //选择充值金额
  selectPrice(e) {
    const that = this;
    let id = e.currentTarget.dataset.id
    var name = '';
    let couponList = []
    for (let i = 0; i < that.data.objectArray.length; i++) {
      if (that.data.objectArray[i].id == id) {
        //当前点击的位置为true即选中
        that.data.objectArray[i].checked = true;
        name = that.data.objectArray[i].name;
        couponList = that.data.objectArray[i].couponList;
      } else {
        //其他的位置为false
        that.data.objectArray[i].checked = false;
      }
    }
    that.setData({
      inputType: false,
      couponList,
      id,
      inpVal: name,
      money: name,
      objectArray: that.data.objectArray,
    })
    that.getBtnMoney()
  },
  //充值
  debounces: utils.throttle(function (e) {
    const that = this;
    if (that.data.inputType) {
      if (!that.data.money) {
        wx.showModal({
          content: '请填写储值金额',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {}
        })
      } else {
        this.recharge()
      }
    } else {
      if (!that.data.inputType && !that.data.id) {
        wx.showModal({
          content: '请选择储值金额',
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {}
        })
      } else {
        this.recharge()
      }
    }

  }, 5000),
  recharge() {
    const that = this;
    let data = {
      orgcode: that.data.orgcode,
      money: that.data.money,
      recharge_money_type_id: that.data.id
    }
    console.log(data, 898989)
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.rechargeDopay, data).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        if (res.data.result.banping == 1) {
          let preOrderId = res.data.result.wx.pre_order
          let merchantId = res.data.result.wx.merchant_id
          let opAppId = 'wx38a3350891b22014'
          wx.openEmbeddedMiniProgram({
            appId: opAppId, // 你要打开的小程序appid
            extraData: { //给B小程序传的参数
              autoPay: 1,
            },
            path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`, // 打开的页面路径，如果为空则打开首页
            envVersion: 'release', // 要打开的小程序版本 develop 开发版 trial 体验版 release 正式版
            success(resData) {
              console.log(resData, 11111)
              // 打开成功

              var listener = (props) => {
                console.log(props, 111)
                console.log(props.referrerInfo, 222)
                console.log(props.referrerInfo.extraData, 333)
                if (!props.referrerInfo.hasOwnProperty('extraData')) {
                  console.log('错误')
                  // wx.showModal({
                  //   content: '付款失败',
                  //   showCancel: false,
                  //   confirmText: '我知道了',
                  //   confirmColor: '#ff5151',
                  //   success(e) {
                  //     if (e.confirm) {

                  //     }
                  //   }
                  // })
                  if (listener) {
                    wx.offAppShow(listener)
                  }
                  wx.setStorageSync('refresh', true)
                  wx.navigateBack({
                    delta: 1
                  })
                  // wx.showModal({
                  //   content: '是否支付成功?',
                  //   cancelText: "未支付",
                  //   cancelColor: "#F56C6C",
                  //   confirmText: '已支付',
                  //   confirmColor: '#67C23A',
                  //   success(e) {
                  //     if (e.confirm) {
                  //       wx.setStorageSync('refresh', true)
                  //       wx.navigateBack({
                  //         delta: 1
                  //       })
                  //       let type = 1;
                  //       let couponType = 0;
                  //       let gifType = 0
                  //       if (that.data.couponList.length > 0) {
                  //         that.data.couponList.forEach(item => {
                  //           if (item.type == 1) {
                  //             couponType = 1;
                  //           }
                  //           if (item.type == 2) {
                  //             gifType = 1;
                  //           }
                  //         })
                  //       }
                  //       if (that.data.couponList.length == 0 || that.data.discount == 1) {
                  //         type = 1
                  //       } else if ((couponType == 1 && gifType == 1) || (couponType == 1 && gifType == 0)) {
                  //         type = 2
                  //       } else if (couponType == 0 && gifType == 1) {
                  //         type = 3
                  //       }
                  //       setTimeout(() => {
                  //         wx.redirectTo({
                  //           url: `/member/pages/rechargeSuccess/rechargeSuccess?orderId=${res.data.result.order}&type=${type}`
                  //         })
                  //       }, 500)
                  //     }
                  //   }
                  // })
                }
                if (props.referrerInfo.extraData.payStatus === '0') {
                  console.log('支付失败')
                  //支付失败
                  //.....
                  wx.showModal({
                    content: '付款失败',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {

                      }
                    }
                  })
                }
                if (props.referrerInfo.extraData.payStatus === '1') {
                  console.log('支付成功')
                  //支付成功
                  //.....
                  wx.setStorageSync('refresh', true)
                  wx.navigateBack({
                    delta: 1
                  })
                  // let type = 1;
                  // let couponType = 0;
                  // let gifType = 0
                  // if (that.data.couponList.length > 0) {
                  //   that.data.couponList.forEach(item => {
                  //     if (item.type == 1) {
                  //       couponType = 1;
                  //     }
                  //     if (item.type == 2) {
                  //       gifType = 1;
                  //     }
                  //   })
                  // }
                  // if (that.data.couponList.length == 0 || that.data.discount == 1) {
                  //   type = 1
                  // } else if ((couponType == 1 && gifType == 1) || (couponType == 1 && gifType == 0)) {
                  //   type = 2
                  // } else if (couponType == 0 && gifType == 1) {
                  //   type = 3
                  // }
                  // setTimeout(() => {
                  //   wx.redirectTo({
                  //     url: `/member/pages/rechargeSuccess/rechargeSuccess?orderId=${res.data.result.order}&type=${type}`
                  //   })
                  // }, 500)
                }
                if (props.referrerInfo.extraData.payStatus === '3') {
                  console.log('用户取消支付')
                  //用户取消支付(订单状态流转为已关闭)
                  //......
                  wx.showModal({
                    content: '付款失败',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#ff5151',
                    success(e) {

                    }
                  })
                }
                if (listener) {
                  wx.offAppShow(listener)
                }
              };
              wx.onAppShow(listener)
            },
            fail(e) {
              console.log(e, 999999)
              // 打开失败
            },
          })
        } else {
          wx.requestPayment({ // 调取支付
            appId: res.data.result.wx.appId,
            timeStamp: res.data.result.wx.timeStamp,
            nonceStr: res.data.result.wx.nonceStr,
            package: res.data.result.wx.package,
            signType: res.data.result.wx.signType,
            paySign: res.data.result.wx.paySign,
            success(prop) {
              if (prop.errMsg == "requestPayment:ok") {
                wx.setStorageSync('refresh', true)
                wx.navigateBack({
                  delta: 1
                })
                // let type = 1;
                // let couponType = 0;
                // let gifType = 0
                // if (that.data.couponList.length > 0) {
                //   that.data.couponList.forEach(item => {
                //     if (item.type == 1) {
                //       couponType = 1;
                //     }
                //     if (item.type == 2) {
                //       gifType = 1;
                //     }
                //   })
                // }
                // if (that.data.couponList.length == 0 || that.data.discount == 1) {
                //   type = 1
                // } else if ((couponType == 1 && gifType == 1) || (couponType == 1 && gifType == 0)) {
                //   type = 2
                // } else if (couponType == 0 && gifType == 1) {
                //   type = 3
                // }
                // setTimeout(() => {
                //   wx.redirectTo({
                //     url: `/member/pages/rechargeSuccess/rechargeSuccess?orderId=${res.data.result.order}&type=${type}`
                //   })
                // }, 500)
              } else {
                wx.showModal({
                  content: res.errMsg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            },
            fail(res) {
              if (res.errMsg == "requestPayment:fail cancel") {
                wx.showToast({
                  title: '支付取消',
                  duration: 2200
                })
              }
            }
          })
        }
      } else {
        wx.showModal({
          content: res.data.msg,
          showCancel: false,
          confirmText: '我知道了',
          confirmColor: '#ff5151',
          success(e) {}
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this
    let sceneObj = utils.parseQueryString(options.scene)
    that.setData({
      orgcode: sceneObj.orgcode ? sceneObj.orgcode : ''
    })
    login.checkLogin().then(res => {
      that.getCardinfoData()
      that.getProvince()
      that.getRechargePay()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.getCardinfoData()
        that.getProvince()
        that.getRechargePay()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})